package com.shanghaionstar.retrofit.utils;

import android.content.Context;

import com.onstar.cn.sqlite.xutil.DbUtils;
import com.onstar.cn.sqlite.xutil.db.sqlite.Selector;
import com.onstar.cn.sqlite.xutil.exception.DbException;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.retrofit.RxRetrofitApp;
import com.shanghaionstar.retrofit.http.cookie.CookieResult;

import java.util.List;


/**
 * 数据缓存
 * 数据库工具类-geendao运用
 * Created by WZG on 2016/10/25.
 */

public class CookieDbUtil {
    private static CookieDbUtil db;
    //    private final static String dbName = "tests_db";
    private DbUtils openHelper;
    private Context context;


    public CookieDbUtil() {
        context = RxRetrofitApp.getApplication();
        openHelper = OnstarApplication.getmDbUtils();
    }


    /**
     * 获取单例
     *
     * @return
     */
    public static CookieDbUtil getInstance() {
        if (db == null) {
            synchronized (CookieDbUtil.class) {
                if (db == null) {
                    db = new CookieDbUtil();
                }
            }
        }
        return db;
    }


    /**
     * 获取可读数据库
     */
//    private SQLiteDatabase getReadableDatabase() {
//        if (openHelper == null) {
//            openHelper = new DaoMaster.DevOpenHelper(context, dbName);
//        }
//        SQLiteDatabase db = openHelper.getReadableDatabase();
//        return db;
//    }

    /**
     * 获取可写数据库
     */
//    private SQLiteDatabase getWritableDatabase() {
//        if (openHelper == null) {
//            openHelper = new DaoMaster.DevOpenHelper(context, dbName);
//        }
//        SQLiteDatabase db = openHelper.getWritableDatabase();
//        return db;
//    }
    public void saveCookie(CookieResult info) {
        try {
            openHelper.save(info);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void updateCookie(CookieResult info) {
        try {
            openHelper.saveOrUpdate(info);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void deleteCookie(CookieResult info) {
        try {
            openHelper.delete(info);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    public CookieResult queryCookieBy(String url) {
        try {
            return openHelper.findFirst(Selector.from(CookieResult.class).where("url", "=", url));
        } catch (DbException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<CookieResult> queryCookieAll() {
        try {
            return openHelper.findAll(CookieResult.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
        return null;
    }
}
